//
//  StoreViewController.m
//  Project_B
//
//  Created by 张闯的mac pro on 15/12/2.
//  Copyright © 2015年 张闯. All rights reserved.
//

#import "StoreViewController.h"
#import "CoreDataManager.h"
#import "ShareTableView.h"
#import "StoreTableViewCell.h"
#import "FifthVideoTableViewCell.h"
#import "FifthVideoDetailViewController.h"
#import "RESideMenu.h"
#import "FifthVideoPlayViewController.h"
#import "Video.h"
#import "ZCSTKPlayer.h"

@interface StoreViewController ()<UITableViewDataSource, UITableViewDelegate>

@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSMutableArray *dataArr;
@property (nonatomic, strong) CoreDataManager *coreDataManager;
@property (nonatomic, assign) NSInteger i;


@end

@implementation StoreViewController

- (void)viewWillAppear:(BOOL)animated
{
    self.dataArr = [self selectVideoModel];
    NSLog(@"~~~%ld", self.dataArr.count);
    if (self.dataArr.count > 0) {
        [self createVideoTableView];
        [self.tableView reloadData];
    } else {
        [self createLabel];
//        [self.tableView removeFromSuperview];
    }
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
//    self.view.backgroundColor = [UIColor colorWithRed:60.0 / 255 green:149.0 / 255 blue:58.0 / 255 alpha:1];
    
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"iconfont-category"] style:UIBarButtonItemStylePlain target:self action:@selector(presentLeftMenuViewController:)];
    [self.navigationItem.leftBarButtonItem setTintColor:[UIColor whiteColor]];
    
    UIImageView *backImg = [[UIImageView alloc] initWithFrame:self.view.frame];
    [self.view addSubview:backImg];
    [backImg setImage:[UIImage imageNamed:@"5.png"]];
    
    //毛玻璃效果
    UIBlurEffect *effect=[UIBlurEffect effectWithStyle:UIBlurEffectStyleLight];
    UIVisualEffectView *effectView=[[UIVisualEffectView alloc]initWithEffect:effect];
    effectView.frame= self.view.frame;
//    effectView.alpha = 0.8;
    [backImg addSubview:effectView];
    
    
    //初始化单例manager
    self.coreDataManager = [CoreDataManager shareInstance];
    NSLog(@"%@", [self.coreDataManager applicationDocumentsDirectory]);
    
}

- (void)createLabel
{
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(100, 250, 200, 60)];
    label.numberOfLines = 0;
    [self.view addSubview:label];
    label.textColor = [UIColor whiteColor];
    label.text = @"还没有收藏的视频,赶快去收藏吧~";
}



- (void)createVideoTableView
{
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, 375, 667 - 64) style:UITableViewStylePlain];
    [self.view addSubview:self.tableView];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.backgroundColor = [UIColor clearColor];
    [self.tableView registerClass:[StoreTableViewCell class] forCellReuseIdentifier:@"cell"];
}

//开启编辑模式
- (void)setEditing:(BOOL)editing animated:(BOOL)animated
{
    [super setEditing:editing animated:animated];
    [self.tableView setEditing:YES];
}

//是否允许编辑
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    return YES;
}

//设置cell样式
- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return UITableViewCellEditingStyleDelete;
}

//删除确认信息
- (NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return @"删除";
}
//判断状态 执行删除操作

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        
        Video *tempModel = [self.dataArr objectAtIndex:indexPath.row];
        //        [self.dataArr removeObject:tempModel];
       // [[ZCDatabaseManager shareInstance] openDB];
        //[[ZCDatabaseManager shareInstance] deleteWithTitle:tempModel.title];
        [self.coreDataManager.managedObjectContext deleteObject:tempModel];
        [self.coreDataManager saveContext];
        
        [self.dataArr removeObjectAtIndex:indexPath.row];
        NSArray *arr = @[indexPath];
        [self.tableView deleteRowsAtIndexPaths:arr withRowAnimation:UITableViewRowAnimationFade];
        
        [self.tableView reloadData];
        NSLog(@"~~%ld", self.dataArr.count);
        if (self.dataArr.count == 0) {
            [self.tableView removeFromSuperview];
            [self createLabel];
        }
    }
}



- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.dataArr.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    StoreTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    cell.fifModel = self.dataArr[indexPath.row];
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:NO];
    FifthVideoPlayViewController *playVC = [[FifthVideoPlayViewController alloc] init];
    [self.tableView removeFromSuperview];
    playVC.titleString = [self.dataArr[indexPath.row] title];
    playVC.playUrl = [self.dataArr[indexPath.row] playUrl];
    [playVC setModalTransitionStyle:UIModalTransitionStyleCrossDissolve];
    [[ZCSTKPlayer shareInstance] pause];
    [self presentViewController:playVC animated:YES completion:^{
        nil;
    }];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 200;
}


- (NSMutableArray *)selectVideoModel
{
    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
    NSEntityDescription *entity = [NSEntityDescription entityForName:@"Video" inManagedObjectContext:self.coreDataManager.managedObjectContext];
    [fetchRequest setEntity:entity];
    // Specify criteria for filtering which objects to fetch
    //    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"title = %@", [self.modelArr[self.i] title]];
    //    [fetchRequest setPredicate:predicate];
    // Specify how the fetched objects should be sorted
    NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"title"
                                                                   ascending:YES];
    [fetchRequest setSortDescriptors:[NSArray arrayWithObjects:sortDescriptor, nil]];
    
    NSError *error = nil;
    NSArray *fetchedObjects = [self.coreDataManager.managedObjectContext executeFetchRequest:fetchRequest error:&error];
    
    NSMutableArray *arr = [NSMutableArray arrayWithArray:fetchedObjects];
    
    if (fetchedObjects == nil) {
        return nil;
    }
    return arr;
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
